<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\admin\validate\Index as IndexValidate;
use app\common\controller\Backend;
use app\common\facade\Token;
use jueqi\Captcha;
use think\facade\Config;

class Index extends Backend
{
    /**
     * 不验证是否登录
     * @var string[]
     */
    protected $noNeedLogin = ['logout', 'login'];
    /**
     * 不验证菜单权限
     * @var string[]
     */
    protected $noNeedPermission = ['index'];

    public function index()
    {
        $adminInfo          = $this->auth->getInfo();
        $adminInfo['super'] = $this->auth->isSuperAdmin();
        unset($adminInfo['token'], $adminInfo['refreshToken']);
        $menus    = $this->auth->getMenus();
        $authList = $this->auth->getRuleList();
        if (!$menus) {
            $this->error(__('No background menu, please contact super administrator!'));
        }
        $cdnUrl = get_cdn_url();
        $this->success('', [
            'adminInfo'  => $adminInfo,
            'menus'      => $menus, // 菜单数组
            'authList'   => $authList, // 权限数组(用于验证按钮权限)
            'siteConfig' => [
                'site_name' => get_sys_config('site_name'),
                'cdn_url'   => full_url($cdnUrl),
                'upload'    => get_upload_config(),
            ],
        ]);
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $request = $this->request;
        // 检查登录态
        if ($this->auth->isLogin()) {
            $this->success(__('You have already logged in. There is no need to log in again~'), [
                'routePath' => '/admin'
            ], 303);
        }
        // 管理员登录验证码配置
        $captchaSwitch = Config::get('backstage.admin_login_captcha');

        // 检查提交
        if ($request->isPost()) {
            $username = $request->post('username', ''); // 用户名
            $password = $request->post('password', ''); // 密码
            $keep     = $request->post('keep', false); // 是否保持会话

            $data = [
                'username'       => $username,
                'password'       => $password,
                'captcha_switch' => $captchaSwitch,
            ];
            if ($captchaSwitch) {
                $data['captcha']   = $request->post('captcha', ''); // 验证码
                $data['captchaId'] = $request->post('captcha_id', ''); // 验证码ID
            }

            // 验证器
            $validate = new IndexValidate();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            // 验证码验证
            if ($captchaSwitch) {
                $captchaObj = new Captcha();
                if (!$captchaObj->check($data['captcha'], $data['captchaId'])) {
                    $this->error(__('Please enter the correct verification code'));
                }
            }
            // 设置日志标题
            AdminLog::setTitle(__('Login'));
            // 设置token过期时间(未开启保存会话时生效)
            $keepTime = Config::get('backstage.keep_time');
            $this->auth->setKeepTime($keepTime);
            // 管理员登录
            $res = $this->auth->login($username, $password, (bool)$keep);
            if ($res === true) {
                // 登录成功
                $this->success(__('Login succeeded!'), [
                    'userinfo'  => $this->auth->getInfo(), // 用户信息
                    'routePath' => '/admin'
                ]);
            } else {
                // 登录失败
                $msg = $this->auth->getError(); // 失败原因
                $msg = $msg ?: __('Incorrect user name or password!');
                $this->error($msg);
            }
        }

        $this->success('', [
            'captcha'    => $captchaSwitch,
            'siteConfig' => [
                'site_name' => get_sys_config('site_name'),
//                'version'   => get_sys_config('version'),
                'cdn_url'   => full_url(),
                'upload'    => get_upload_config(),
            ],
        ]);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $request = $this->request;
        if ($request->isPost()) {
            $refreshTokenName   = Config::get("backstage.refresh_token_name");
            $refreshToken = $request->post($refreshTokenName, '');
            if ($refreshToken) {
                // 删除token
                Token::delete((string)$refreshToken);
            }
            // 退出登录
            $this->auth->logout();
            $this->success(__("Log out successfully"));
        }
    }
}
